angular.module('app')
  .directive('uiSearchMenu', ['$document', function($document) {
    return {
      restrict: 'AC',
      link: function(scope, el, attr) {
			var target = attr.uiSearchMenu;
			var events = attr.searchEvents;
			if(events == null){
				events = 'click';
			}else{
				events = events.split(',');
			}
			el.next().next('.close').on('click',function(event){
				//el.val('');
				angular.element(this).hide();
			});
			el.on(events.join(' '), function(e) {
				if(el.is('input')){
					if(angular.element.trim(el.val()) != ''){
						el.next().next('.close').show();
					}
				}
			    angular.element(''+ target).addClass("search-menu-open");
				$document.on("mousedown.search-menu", function(event){
					var v = '.search-menu,.cg-busy';
					if(angular.element( event.target ).closest(v).length != 0){
						/*if(angular.element(event.target).is(':checkbox')){
							angular.element(event.target).attr('checked', !event.target.checked);
						}else if(angular.element(event.target).attr('checkbox') !== undefined){
							var checked = angular.element(event.target).prev(':checkbox')[0].checked;
							angular.element(event.target).prev(':checkbox')[0].checked = !checked;
//							$(event.target).prev(':checkbox').attr('checked', !checked);
						}*/
					}else if ( !angular.element( event.target ).closest( angular.element(v).add(el) ).length ) {
						angular.element(''+ target).removeClass("search-menu-open");
						
						$document.off("mousedown.search-menu");
					}
				});
			});
      }
    };
}]);
